//
//  TJLoginController.m
//  CrossBorderPayment
//
//  Created by hc-101 on 2020/6/9.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJLoginController.h"
#import "TJForgetPasswordController.h"
#import "TJRegisteredController.h"
#import "TJLanguageSettingController.h"
#import "TJSelectCityController.h"

@interface TJLoginController ()<UITextFieldDelegate>



@property (weak, nonatomic) UITextField *emailTextField;
@property (weak, nonatomic) UITextField *phoneTextField;

@property (weak, nonatomic) UITextField *passwordTextField;
@property (weak, nonatomic) UIButton *areaButton;
@property (assign, nonatomic) BOOL isEmailLogin;
@property (weak, nonatomic) UILabel *mailLoginLabel;
@property (copy, nonatomic) NSString *areaCode;


@end

static NSString * const testCell = @"testCell";

@implementation TJLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.lineView.hidden = YES;
    self.navigationBar.rightBarButton = [TJButtonBarButton barButtonWithTitle:@"设置语言".localizedString target:self action:@selector(didNavBarRightButton)];
    
    UILabel *welComeLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(24) color:UIColor_Hex(0x262626) title:[NSString stringWithFormat:@"%@欢迎您".localizedString, [Tools appName]] textAlignment:NSTextAlignmentLeft];
    [welComeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(36);
        make.top.offset(KNavBarHight + 46);
    }];
    
    _areaCode = @"+86";
    
    UIButton *areaButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(14) color:UIColor_Hex(0x262626) title:_areaCode];
    [areaButton setImage:[UIImage imageNamed:@"areaArrowIcon"] forState:UIControlStateNormal];
    [areaButton setImage:[UIImage imageNamed:@"areaArrowIcon"] forState:UIControlStateHighlighted];
    [areaButton setImagePosition:LXMImagePositionRight spacing:4];
    [areaButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentLeft)];
    [areaButton addTarget:self action:@selector(didClickAreaButton) forControlEvents:UIControlEventTouchUpInside];
    [areaButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(welComeLabel);
        make.top.equalTo(welComeLabel.mas_bottom).offset(44);
        make.width.offset(55);
        make.height.offset(24);
    }];
    
    UITextField *phoneTextField = [UITextField tj_addToView:self.view];
    phoneTextField.placeholder = @"请输入手机号码".localizedString;
    phoneTextField.font = UIFont_Px(15);
    phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(areaButton.mas_right).offset(16);
        make.centerY.equalTo(areaButton);
        make.height.offset(34);
        make.right.offset(-36);
    }];
    
    UITextField *emailTextField = [UITextField tj_addToView:self.view];
    emailTextField.placeholder = @"请输入您的邮箱账户".localizedString;
    emailTextField.font = UIFont_Px(15);
    emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    [emailTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(welComeLabel);
        make.centerY.equalTo(areaButton);
        make.height.offset(34);
        make.right.offset(-36);
    }];
    
    UIView *lineView = [UIView tj_addToView:self.view];
    lineView.backgroundColor = UIColor_Hex(0xE5E5E5);
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(areaButton);
        make.right.equalTo(phoneTextField);
        make.height.offset(1);
        make.top.equalTo(phoneTextField.mas_bottom).offset(2);
    }];
    
    UITextField *passwordTextField = [UITextField tj_addToView:self.view];
    passwordTextField.placeholder = @"请输入您的密码".localizedString;
    passwordTextField.secureTextEntry = YES;
    passwordTextField.font = UIFont_Px(15);
    passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    passwordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(areaButton);
        make.top.equalTo(lineView.mas_bottom).offset(16);
        make.height.offset(34);
        make.right.equalTo(phoneTextField);
    }];
    
    UIView *passwordLineView = [UIView tj_addToView:self.view];
    passwordLineView.backgroundColor = UIColor_Hex(0xE5E5E5);
    [passwordLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(areaButton);
        make.right.equalTo(passwordTextField);
        make.height.offset(1);
        make.top.equalTo(passwordTextField.mas_bottom).offset(2);
    }];
    
    UIButton *LoginButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"登录".localizedString];
    LoginButton.backgroundColor = UIColor_Hex(0x2C6CC7);
    [LoginButton shearRoundedCornersWithRadiu:22];
    [LoginButton addTarget:self action:@selector(didClickLoginButton) forControlEvents:UIControlEventTouchUpInside];
    [LoginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(phoneTextField);
        make.left.equalTo(passwordTextField);
        make.height.offset(44);
        make.centerX.offset(0);
        make.top.equalTo(passwordLineView.mas_bottom).offset(30);
    }];
    
    
    UILabel *forgetPasswordLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor_Hex(0x262626) title:@"忘记密码?".localizedString textAlignment:NSTextAlignmentLeft];
    [forgetPasswordLabel addTapGesturesWithTarget:self action:@selector(tapForgetPasswordLabel)];
    [forgetPasswordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(LoginButton);
        make.top.equalTo(LoginButton.mas_bottom).offset(14);
    }];
    
    UILabel *mailLoginLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor_Hex(0x262626) title:@"邮箱登录".localizedString textAlignment:NSTextAlignmentLeft];
    [mailLoginLabel addTapGesturesWithTarget:self action:@selector(tapLoginWayLabel)];
    [mailLoginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(LoginButton);
        make.centerY.equalTo(forgetPasswordLabel);
    }];
    
    UILabel *tipLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor_Hex(0x8F8F8F) title:@"您还没有账户，请注册".localizedString textAlignment:NSTextAlignmentLeft];
    tipLabel.attributedText = [tipLabel.text attributedStringWithNumberString:@"注册(registered)".localizedString numberStringColor:UIColor.tj_mainColor];
    [tipLabel addTapGesturesWithTarget:self action:@selector(tapTipLabel)];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(LoginButton.mas_bottom).offset(100);
        make.centerX.offset(0);
    }];
    
    _areaButton = areaButton;
    _phoneTextField = phoneTextField;
    _emailTextField = emailTextField;
    _passwordTextField = passwordTextField;
    _mailLoginLabel = mailLoginLabel;
    
    self.isEmailLogin = NO;
    
    if (_isEmailLogin) {
        _emailTextField.text = [USERDEFAULTS objectForKey:userEmail];
    } else {
        _phoneTextField.text = [USERDEFAULTS objectForKey:userPhone];
    }
}
/**区域切换点击 */
- (void)didClickAreaButton {
    TJSelectCityController *selectCityController = [[TJSelectCityController alloc] init];
    [selectCityController setSelectComplete:^(TJSelectCityModel * _Nonnull model) {
        [self.areaButton setTitle:model.code forState:UIControlStateNormal];
        [self.areaButton setImagePosition:LXMImagePositionRight spacing:4];
        self.areaCode = model.code;
    }];
    [self presentViewController:selectCityController animated:YES completion:nil];
}
/**语言切换 */
- (void)didNavBarRightButton {
    [self presentViewController:[[TJLanguageSettingController alloc] init] animated:YES completion:nil];
}

- (void)setIsEmailLogin:(BOOL)isEmailLogin {
    _isEmailLogin = isEmailLogin;
    
    _emailTextField.hidden = !isEmailLogin;
    _phoneTextField.hidden = isEmailLogin;
    _areaButton.hidden = isEmailLogin;
    _mailLoginLabel.text = isEmailLogin ? @"手机号登录".localizedString : @"邮箱登录".localizedString;
    
    
}
/**邮箱登录切换 */
- (void)tapLoginWayLabel {
    
    self.isEmailLogin = !self.isEmailLogin;
}
/**忘记密码点击 */
- (void)tapForgetPasswordLabel {
    
    TJForgetPasswordController *forgetPasswordController = [[TJForgetPasswordController alloc] init];
    [self.navigationController pushViewController:forgetPasswordController animated:YES];
}
/**登录点击 */
- (void)didClickLoginButton {
    
    NSString *password = _passwordTextField.text;
    
    NSMutableDictionary *parameters = @{}.mutableCopy;
    
    [self.view endEditing:YES];
    
    
    if (_isEmailLogin) {//是否是邮箱登录
        
        NSString *email = _emailTextField.text;
        
        if (!email.length) {
            [TJHud showAutoHideMessage:_emailTextField.placeholder];
            return;
        }
        
        if (!password.length) {
            [TJHud showAutoHideMessage:_passwordTextField.placeholder];
            return;
        }
        
        
        [parameters setObject:email forKey:@"phMail"];
        
        [parameters setObject:password forKey:@"password"];
        
    } else {
        NSString *phone = _phoneTextField.text;
        
        if (!phone.length) {
            [TJHud showAutoHideMessage:_phoneTextField.placeholder];
            return;
        }
        
        if (!password.length) {
            [TJHud showAutoHideMessage:_passwordTextField.placeholder];
            return;
        }
        
        [parameters setObject:phone forKey:@"phMail"];
        
        [parameters setObject:password forKey:@"password"];
    }
    
    
    
    [self showloading];
    
    /**获取token userId */
    [TJNetworking.shareNetworking POSTNew:@"member/member/login" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary  *data1) {
        
        [self hiddenloading];
        
        if (self.isEmailLogin) {//邮箱登录
            [USERDEFAULTS setObject:self.emailTextField.text forKey:userEmail];
        } else {
            [USERDEFAULTS setObject:self.phoneTextField.text forKey:userPhone];
        }
        
         TJUserInfo *userInfo = [TJUserInfo readInfo];
        userInfo.token = data1[@"token"];
        userInfo.userId = data1[@"userId"];
        
         
        
        //获取用户信息
        [TJNetworking.shareNetworking GET:@"member/member/getMember" parameters:@{@"userId": userInfo.userId} success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
            TJUserInfo *userInfo = [TJUserInfo mj_objectWithKeyValues:data];
            userInfo.token = data1[@"token"];
            
            [userInfo saveInfo];
            
            //保存本地是否登录
            [USERDEFAULTS setBool:YES forKey:isLogin];
            //通知登录成功
            [[NSNotificationCenter defaultCenter] postNotificationName:loginSucceedNotification object:nil];
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}
/**注册点击 */
- (void)tapTipLabel {
    
    TJRegisteredController *registeredController = [[TJRegisteredController alloc] init];
    [self.navigationController pushViewController:registeredController animated:YES];
}



@end
